package com.hehe.Config;

import com.hehe.Tool.LoginUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {

        String token = LoginUtils.getTokenFromCookies(request);  // 从请求的 Cookies 中获取 token
        String userId = LoginUtils.verifyTokenAndGetUserId(token);   // 验证 token 并获取用户的 userId

        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized
            response.setContentType("text/html;charset=UTF-8");  // 设置响应类型为 HTML
            // response.getWriter().write(" <h1> Error : 请登录 - Please login - <a href='/login'>立即登录 Login </a></h1> ");
            response.sendRedirect("/login");  // 重定向到登录页面
            return false;
        }

        request.setAttribute("loggedUserId", userId);
        return true;
    }
}

